package soa;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Displayable;
import midlet.MidletCielsa;

/**
 *
 * @author Dikas
 */
public class ServicioWeb implements Runnable {

    protected String URL;
    protected String[][] entradas;
    protected MidletCielsa midlet;
    protected Displayable previousDisplay;
    protected String result;

    public ServicioWeb(String URL, String[][] entradas, MidletCielsa midlet, Displayable previousDisplay) {
        this.URL = URL;
        this.entradas = entradas;
        this.midlet = midlet;
        this.previousDisplay = previousDisplay;
    }

    public void run() {
        try {
            envio();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error: " + e.toString());
            networkError(e.toString());
        }
    }

    public void start() {
        Thread t = new Thread(this);
        try {
            t.start();
        } catch (Exception e) {
            System.err.println("Error: " + e.toString());
            e.printStackTrace();
            networkError(e.toString());
        }
    }

    protected void envio() throws IOException {
        InputStream is = null;
        StringBuffer sb = null;
        HttpConnection http = null;

        try {
            if (entradas != null) {
                if (entradas[0].length == 2 && entradas.length > 0) {
                    URL += "?";
                    for (int i = 0; i < entradas.length; i++) {
                        if (i != 0) {
                            URL += "&";
                        }
                        URL += entradas[i][0] + "=" + entradas[i][1];
                    }

                }
            }            
            URL = EncodeURL(URL);
            System.out.println("URL: " + URL);
            http = (HttpConnection) Connector.open(URL);
            http.setRequestMethod(HttpConnection.GET);
            if (http.getResponseCode() == HttpConnection.HTTP_OK) {
                sb = new StringBuffer();
                int ch;
                is = http.openInputStream();
                while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                }
            } else {
                networkError();
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.toString());
            networkError(e.toString());
        } finally {
            if (is != null) {
                is.close();
            }
            if (sb != null) {
                result = sb.toString();
            } else {
                networkError();
            }
            if (http != null) {
                http.close();
            }
        }
        if (result == null) {
            result = "";
        }
        else
            result = result.trim();
//        System.out.println("Resultado:\n" + result);
        if (result.compareTo("") != 0) {
            proceso();
        } else {
            networkError();
        }
    }

    protected void proceso() {
    }

    protected Displayable getCurrentDisplay() {
        Displayable d = midlet.getCurrentDisplay();
        if (d.getClass().getName().equals("javax.microedition.lcdui.Alert")) {
            d = previousDisplay;
        }
        return d;
    }

    protected String EncodeURL(String URL) {
        URL = replace(URL, 'à', "%E0");
        URL = replace(URL, 'è', "%E8");
        URL = replace(URL, 'é', "%E9");
        URL = replace(URL, 'ì', "%EC");
        URL = replace(URL, 'ò', "%F2");
        URL = replace(URL, 'ù', "%F9");
        URL = replace(URL, '$', "%24");
        URL = replace(URL, '#', "%23");
        URL = replace(URL, '£', "%A3");
        URL = replace(URL, '@', "%40");
        URL = replace(URL, '\'', "%27");
        URL = replace(URL, ' ', "%20");

        return URL;
    }

    protected String replace(String source, char oldChar, String dest) {
        String ret = "";
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) != oldChar) {
                ret += source.charAt(i);
            } else {
                ret += dest;
            }
        }
        return ret;
    }

    protected void networkError() {
        midlet.showInfo("Network error, try later", getCurrentDisplay());
    }

    protected void networkError(String msg) {
        midlet.showInfo(msg, getCurrentDisplay());
    }
}
